package binarySearch;

public class findMin {
    public int findMin(int[] nums) {
        // 首先判断头尾元素大小关系，看数组是否变化了
        if (nums[0] <= nums[nums.length - 1]) {
            // 长度为1or顺序
            return nums[0];
        }
        // if (nums.length == 2) {
        // return Math.min(nums[0], nums[1]);
        // }
        // 发生了不对称的旋转
        int left = 0, right = nums.length - 1, mid = 0;
        int ans = nums[right];
        while (left <= right) {
            mid = (left + right) / 2;
            if (nums[mid] >= nums[left] && nums[mid] > nums[right]) {
                left = mid + 1;
            } else if (nums[mid] >= nums[left] && nums[mid] < nums[right]) {
                right = mid - 1;
                ans = mid;
            } else if (nums[mid] <= nums[left] && nums[mid] <= nums[right]) {
                if (nums[mid] < nums[mid - 1] && mid + 1 == nums.length) {
                    ans = mid;
                    return nums[ans];
                } else if (nums[mid] < nums[mid - 1] && nums[mid] < nums[mid + 1]) {
                    ans = mid;
                    return nums[ans];
                }else{

                    right=mid-1;
                    ans=mid;
                }
            }

        }
        return nums[ans];
    }

    public static void main(String[] args) {
        // int[] nums = new int[ ]{3,4,5,1,2};
        // int[] nums = new int[ ]{4,5,1,2,3};
        // int[] nums = new int[ ]{1,2,3,4};
        // int[] nums = new int[ ]{4,5,6,7,0,1,2};
        // int[] nums = new int[] { 4,3 };
        // int[] nums = new int[] { 3,4,1,2 };
        int[] nums = new int[] { 5, 1, 2, 3, 4 };
        // int[] nums = new int[] { 7,1,2,3,4,5,6 };
        findMin obj = new findMin();
        System.out.println(obj.findMin(nums));
    }
}
